/**
 * 532. K-diff Pairs in an Array
 * https://leetcode.cn/problems/k-diff-pairs-in-an-array/
 */

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number}
 */
function findPairs(nums, k) {
  nums.sort((a, b) => a - b);
  let count = 0;
  if (!k) {
    for (let i = 1; i < nums.length; i += 1) {
      if (nums[i] === nums[i - 1]) {
        count += 1;
        const flag = nums[i];
        for (i += 1; i < nums.length; i += 1) {
          if (nums[i] !== flag) {
            break;
          }
        }
      }
    }
    return count;
  }
  let last;
  const set = new Set();
  for (let i = 0; i < nums.length; i += 1) {
    if (nums[i] === last) {
      continue;
    }
    if (set.has(nums[i] - k)) {
      count += 1;
    }
    set.add(nums[i]);
    last = nums[i];
  }
  return count;
}

console.log(findPairs([3, 1, 4, 1, 5], 2) === 2);
console.log(findPairs([1, 2, 3, 4, 5], 1) === 4);
console.log(findPairs([1, 3, 1, 5, 4], 0) === 1);
console.log(findPairs([1, 1, 1, 1, 1], 0) === 1);
console.log(findPairs([1, 1, 1, 2, 2], 0) === 2);
